import { getUserInfoApi, updateUserApi } from "@/api";
import Taro from "@tarojs/taro";
import { setUser } from "./auth";
import { UserType } from "@/types";

export const toast = (
  title?: string = "操作成功",
  icon?: "success" | "error" | "loading" | "none" = "none",
  duration? = 3000
) =>
  Taro.showToast({
    title,
    icon,
    duration,
  });

export function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

export function isValidPhone(phone: string): boolean {
  const phoneRegex = /^1[3-9][0-9]{9}$/;
  return phoneRegex.test(phone);
}

export function copyToClipboard(text) {
  Taro.setClipboardData({
    data: text,
    success: () => toast("复制成功"),
    fail: () => toast("复制失败"),
  });
}

export function chooseImg(count = 1): Promise<string> {
  return new Promise((resolve, reject) => {
    Taro.chooseImage({
      count,
      sourceType: ["album", "camera"],
      success: (res) => {
        resolve(res.tempFilePaths[0]);
      },
      fail: reject,
    });
  });
}

export function updateUser(params) {
  return updateUserApi(params).then((res: UserType) => {
    toast("修改成功");
    return getUserInfoApi(res.ID);
  });
}

export function getUserInfo(id) {
  getUserInfoApi(id).then((res: UserType) => {
    setUser(res);
    return res;
  });
}
